import 'package:flutter/widgets.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/models/jzx_media_data.dart';
import 'package:hockey/pages/jzx_posts/widgets/jzx_images_view.dart';
import 'package:hockey/services/jzx_app.dart';
import 'package:hockey/services/jzx_config.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/dialogs/jzx_photo_sheet.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class JzxPostsController extends GetxController {
  /// 列表
  var items = <JzxMediaData>[].obs;
  var originItems = <JzxMediaData>[];

  var contentlength = 0.obs;
  final content = TextEditingController();
  final title = TextEditingController();

  final maxCount = 6;
  final images = <AssetEntity>[].obs;

  @override
  void onInit() {
    super.onInit();
    fetchData();

    content.addListener(() {
      contentlength.value = content.text.length;
    });

    JzxAppService.bus.on<RefreshPostLike>().listen((event) {
      // items.value = event.items;
      fetchData();
    });

    // 过滤拉黑用户
    JzxAppService.bus.on<RefreshBlockUsers>().listen((event) {
      fliterUser();
    });
  }

  /// 过滤用户
  fliterUser() {
    items.value = List.from(
      originItems
          .where((element) =>
              !JzxConfigService.to.blockList.contains(element.user.userId))
          .toList(),
    );
  }

  void fetchData() async {
    originItems = await JzxConfigService.to.getCurPostList();
    items.value = List.from(
      originItems
          .where((element) =>
              !JzxConfigService.to.blockList.contains(element.user.userId))
          .toList(),
    );
  }

  /// 更新数据
  updatePost(JzxMediaData item) async {
    JzxConfigService.to.updatePostList(item);
  }

  void likeOrCancel(JzxMediaData item, int index) {
    final state = item.isLiked; //
    if (state == false) {
      JzxUserService.to.updateUnlockConditions(2);
    }
    item = item.copyWith(
      isLiked: !state,
      like: item.like + (state ? -1 : 1),
    );
    items.value = List.of(items.value)..[index] = item;

    updatePost(item);
  }

  /// 发布帖子
  Future submitPost() async {
    if (content.text.isEmpty || images.isEmpty || title.text.isEmpty) {
      showMessage('Images and labels are required！');
      return;
    }

    try {
      showLoading();

      var temp = <String>[];

      for (var item in images) {
        final file = (await item.file);
        final path = await saveFile(file!);
        temp.add(path);
      }

      final item = JzxMediaData(
        title: title.text,
        content: content.text,
        cover: temp.removeAt(0),
        url: temp.join(','),
        // images: images.map((e) => e.fileUrl).toList(),
        id: JzxConfigService.to.postList.length + 11000,
        author: JzxUserService.to.author,
        // bindingUser: JzxUserService.to.uid,
        user: JzxUserService.to.authorData,
      );

      updatePost(item);
      items.insert(0, item);
      hideLoading();

      images.clear();
      content.clear();
      title.clear();

      showMessage('Successfully');
    } catch (e) {
      // log('$e');
    }
  }

  /// 选择图像
  void pickOthersInfo() {
    Get.bottomSheet(
      JzxImagesView(this, () async {
        await submitPost();
        Get.back();
      }),
      backgroundColor: myAppColors.barrierColor,
      isScrollControlled: true,
    );
  }

  void pickerImages(BuildContext context) async {
    final res = await JzxPhotoSheet.show(
      context,
      maxAssets: maxCount - images.length,
    );

    if (res?.isNotEmpty == true) {
      showLoading();
      images.addAll(res!);
      hideLoading();

      // for (var item in res!) {
      // final file = await item.file;
      // }
    }
  }

  void removeImage(int i) {
    images.removeAt(i);
  }
}
